<template>
  <el-dropdown trigger="click" class="international" @command="handleSetLanguage">
    <div>
      <svg-icon class-name="international-icon" icon-class="language" />
    </div>
    <el-dropdown-menu slot="dropdown">
      <el-dropdown-item :disabled="language==='zh'" command="zh">
        中文
      </el-dropdown-item>
      <el-dropdown-item :disabled="language==='zh-TW'" command="zh-TW">
        繁體中文
      </el-dropdown-item>
      <el-dropdown-item :disabled="language==='en'" command="en">
        English
      </el-dropdown-item>
    </el-dropdown-menu>
  </el-dropdown>
</template>

<script>
import Cookies from 'js-cookie'
import { changeLanguage } from '@/api/common'

export default {
  computed: {
    language() {
      return this.$store.getters.language
    }
  },
  methods: {
    async handleSetLanguage(lang) {
      try {
        console.log('Switching language to:', lang)
        console.log('Current i18n locale:', this.$i18n.locale)
        
        // 1. 更新Vue i18n locale
        this.$i18n.locale = lang
        console.log('Updated i18n locale to:', this.$i18n.locale)
        
        // 2. 更新Vuex store
        this.$store.dispatch('app/setLanguage', lang)
        console.log('Updated store language to:', this.$store.getters.language)
        
        // 3. 更新Cookie
        Cookies.set('language', lang)
        console.log('Updated cookie language to:', Cookies.get('language'))
        
        // 4. 调用后端接口切换语言
        const response = await changeLanguage(lang)
        console.log('Backend response:', response)
        
        // 5. 重新生成路由（菜单）
        await this.$store.dispatch('permission/GenerateRoutes')
        console.log('Routes regenerated with new language')
        
        // 6. 显示成功消息
        this.$message({
          message: lang === 'zh' ? '语言切换成功' : (lang === 'zh-TW' ? '語言切換成功' : 'Language changed successfully'),
          type: 'success'
        })
        
        // 7. 触发全局事件，通知其他组件更新
        this.$root.$emit('language-changed', lang)
        
        // 8. 强制更新当前页面组件
        this.$forceUpdate()
        
        // 9. 强制刷新页面，确保所有内容切换语言
        window.location.reload()
        
      } catch (error) {
        console.error('Language change failed:', error)
        this.$message({
          message: lang === 'zh' ? '语言切换失败' : (lang === 'zh-TW' ? '語言切換失敗' : 'Failed to change language'),
          type: 'error'
        })
      }
    }
  }
}
</script>

<style scoped>
.international-icon {
  font-size: 18px;
  cursor: pointer;
  vertical-align: text-bottom;
}
</style> 